//
//  Transform.m
//  Bus
//
//  Created by wangjiajia on 13-11-28.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "Transform.h"
#import "MBProgressHUD.h"
#import "Tools.h"
#import "WebServicesUtils.h"
#import "ASIHTTPRequestDelegate.h"
#import "ASIHTTPRequest.h"
#import "UserForm.h"
#import "JsonParser.h"
#import "AutoScrollUILabel.h"
#import "RepDetail.h"
#import "UIButton+Bootstrap.h"
#import "DXAlertView.h"
#import "TransAlertView.h"
#import "TransView.h"
#import "NSString+replace.h"
#import "ProcessResult.h"
#import "SpNext.h"
#import "SpBhNext.h"
extern int userId;
extern NSString* userName;
@interface Transform (){
    MBProgressHUD* hud;
    UserForm* formInfo;
    ASIHTTPRequest* globalRequest;
    NSString* filterHTML;
}

@end

@implementation Transform

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back.png"] forState:UIControlStateNormal];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back_selected.png"] forState:UIControlStateHighlighted];
    
    [leftButton setTitle:@" 返回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"-" size:18];
    [leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [leftButton addTarget:self action:@selector(backTo) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    self.navigationItem.leftBarButtonItem = back;
    
    //设置背景
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"view_bg.png"] ]];
    //设置标题
    if([self.state isEqualToString:@"未办理"]){
        self.navigationItem.title=@"工作办理";
        //设置办理按钮
        UIButton *transBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        [transBtn clearStyle];
        [transBtn setTitle:@"办理" forState:UIControlStateNormal];
        transBtn.titleLabel.font=[UIFont fontWithName:@"-" size:18];
        [transBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [transBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [transBtn addTarget:self action:@selector(transForm) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *transBtnItem = [[UIBarButtonItem alloc] initWithCustomView:transBtn];
        self.navigationItem.rightBarButtonItem=transBtnItem;
        
    }else if([self.state isEqualToString:@"已办理"]){
        self.navigationItem.title=@"办理查看";
    }else if([self.state isEqualToString:@"已委托"]){
        self.navigationItem.title=@"委托查看";
    }
    if(!hud)
        hud=[[MBProgressHUD alloc] initWithView:self.view];
    [Tools showHUD:@"正在获取数据..." andView:self.view andHUD:hud];
    //根据state，id 初始加载界面内容
    globalRequest= [WebServicesUtils getUserFormByID:self.Id andState:self.state withDelegete:self];
    //NSLog(@"%@",NSStringFromCGRect(self.formContent.frame));
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}



-(void)viewWillDisappear:(BOOL)animated{
    if (globalRequest) {
        //NSLog(@"界面即将消失,golablRequest仍然请求中,取消之!");
        [globalRequest clearDelegatesAndCancel];
    }
    [super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setFormTitle:nil];
    [self setFormPubInfo:nil];
    [self setFormContent:nil];
    self.state=nil;
    [super viewDidUnload];
}
#pragma mark-自定义函数实现

-(void)transForm{
    if( [self.formContent isLoading]){
        [Tools toastNotification:@"数据加载中,请稍后..." andView:self.view andLoading:YES andIsBottom:NO];
        return;
    }
    
    NSString* processStr  =[self.formContent stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('wjj')[0].innerHTML"];
    if([processStr isEqualToString:@""]){
        [Tools toastNotification:@"没有表单数据待处理!" andView:self.view andLoading:NO andIsBottom:NO];
        return;
    }
    
    //1、同步Dom对象的值
    [self.formContent stringByEvaluatingJavaScriptFromString:@"JSHtml();"];//OK
    
    //1、系统自带（逛了一圈，3天左右时间，怎么就没有类似Android的popWindow呢）
    UIAlertView* alertView=nil;
    //选项的判断：保存，通过，驳回
    NSInteger m=  formInfo.JBRObjectId.length;
    NSInteger n=[formInfo.JBRObjectId stringByReplacingOccurrencesOfString:@"," withString:@""].length;
    
    NSInteger k=m-n;
    ////NSLog(@"[%@|%@] 还剩下%d人处理",formInfo.JBRObjectId,[formInfo.JBRObjectId stringByReplacingOccurrencesOfString:@"," withString:@""],k);
    float version=[[[UIDevice currentDevice] systemVersion] floatValue];
    ////NSLog(@"%f",version);
    if(k<=1)//还剩下1人处理，保存，通过，驳回
    {
        
        alertView=[[UIAlertView alloc] initWithTitle:version>=7.0f?@"处理选项":@"" message:version>=7.0f?@"审批意见,可以不填写。":@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存",@"通过",@"驳回", nil];
        alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
        alertView.backgroundColor=[UIColor clearColor];//ios7下看不到背景色，ios6下可以看到
        
    }else{//多人处理
        if([formInfo.SpModle isEqualToString:@"只要有一人通过审批即可向下流转"])
        {//通过可见
            alertView=[[UIAlertView alloc] initWithTitle:version>=7.0f?@"处理选项":@"" message:version>=7.0f?@"审批意见,可以不填写。":@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存",@"通过",@"驳回", nil];
            alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
            alertView.backgroundColor=[UIColor clearColor];
        }else{//通过不可见
            alertView=[[UIAlertView alloc] initWithTitle:version>=7.0f?@"处理选项":@"" message:version>=7.0f?@"审批意见,可以不填写。":@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存",@"驳回", nil];
            alertView.alertViewStyle=UIAlertViewStylePlainTextInput;
            alertView.backgroundColor=[UIColor clearColor];
        }
    }
    [alertView show];
    
    
    //2、基于开源控件
    //        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"办理" contentText:@"You have bought something" leftButtonTitle:@"Ok" rightButtonTitle:@"Fine"];
    //        alert.leftBlock = ^() {
    //            //NSLog(@"left button clicked");
    //        };
    //        alert.rightBlock = ^() {
    //            //NSLog(@"right button clicked");
    //        };
    //        alert.dismissBlock = ^() {
    //            //NSLog(@"Do something interesting after dismiss block");
    //        };
    //        [alert show];
    
    //3、UIAlertView的扩展类,失败告场....
    //    TransAlertView *alertView=[[TransAlertView alloc] initWithTitle:@"办理选项" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"保存",@"通过",@"驳回", nil];
    //    [alertView show];
    
    //4、try idea，无法移除视图，哎。。。
    //    TransView* transView= (TransView*)[[[NSBundle mainBundle] loadNibNamed:@"TransView" owner:Nil options:Nil] lastObject];
    //    transView.saveBlock=^(){
    //
    //    };
    //    [transView show];
    
    
    //NSString* test1  =[self.formContent stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
    ////NSLog(@"\n%@",test1);
    
    //NSString* test2  =[self.formContent stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];//即使没有HTML标签,会自动补全
    ////NSLog(@"\n%@",test2);
}


#pragma mark- UIAlertViewDelegate代理方法实现
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //NSLog(@"输入%@,%d=%@",[alertView textFieldAtIndex:0].text,buttonIndex,[alertView buttonTitleAtIndex:buttonIndex]);
    //     输入,1=保存   保存
    //     输入,2=通过   驳回
    //     输入,3=驳回
    //     输入,0=取消   取消
    //switch 只能int类型表达式 这里int判断反而繁琐
    if([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"保存"]){
        //保存的表单中不能出现双引号",否则和Json参数格式混淆.所以需要替换为
        //@"'",但是涉及只读替换。导致例如，name="123" 可以替换，name='123'替换不了。另外sql中，单引号'表示为两个单引号''
        //或者@"\\\\\"",即转义的双引号 \"。经测试，ios里需要\\\\才能转义。
        //通过sql的监听，可以看到传递的字符串是否正确。
        NSString* formHTML=[[self.formContent stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('wjj')[0].innerHTML"] replaceRegex:@"\"" :@"\\\\\""];
        
        globalRequest=[WebServicesUtils processSave:formInfo.Id andUserId:userId andUserName:userName andFileContent:formHTML andSpContent:[alertView textFieldAtIndex:0].text withDelegete:self];
        
    }else if ([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"通过"]){
        globalRequest=[WebServicesUtils processSaveAndPass:formInfo.Id andUserId:userId andUserName:userName andFileContent:[[self.formContent stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('wjj')[0].innerHTML"] replaceRegex:@"\"" :@"\\\\\""] andSpContent:[alertView textFieldAtIndex:0].text withDelegete:self];
        
    }else if([[alertView buttonTitleAtIndex:buttonIndex] isEqualToString:@"驳回"]){
        globalRequest=[WebServicesUtils processSaveAndReject:formInfo.Id andUserId:userId andUserName:userName andFileContent:[[self.formContent stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('wjj')[0].innerHTML"] replaceRegex:@"\"" :@"\\\\\""]andSpContent:[alertView textFieldAtIndex:0].text withDelegete:self];
    }
    
}
#pragma mark- 网络处理

-(void)requestFinished:(ASIHTTPRequest *)request{
    if(hud){
        [hud hide:YES];
    }
    if(request.tag==0){//表单内容请求结束
        NSString* responseStr=[request responseString];
        ////NSLog(@"responseStr=%@",responseStr);
        formInfo=[JsonParser parseAsUserForm:responseStr];
        float wordWidth=[formInfo.Name sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT"size:20]].width;
        float screenWidth=[UIScreen mainScreen].bounds.size.width;
        self.formTitle.frame=CGRectMake(0,self.formTitle.frame.origin.y, wordWidth>screenWidth?wordWidth:screenWidth, 30);//设置宽度，便于内部drawRect判断是否滚动
        //self.formTitle.textAlignment=UITextAlignmentCenter;//IB中设置
        self.formTitle.text=formInfo.Name;
        if([self.state isEqualToString:@"已委托"]){
            self.formPubInfo.text=  [NSString stringWithFormat:@"发起人:%@ 委托时间:%@",formInfo.FqUserName,formInfo.NowTimes];
        }else if([self.state isEqualToString:@"已办理"]) {
            self.formPubInfo.text=  [NSString stringWithFormat:@"发起人:%@ 最近办理:%@",formInfo.FqUserName,formInfo.NowTimes];
        }
        else  {
            self.formPubInfo.text=  [NSString stringWithFormat:@"发起人:%@ 发起时间:%@",formInfo.FqUserName,formInfo.NowTimes];
        }
        //只有办理时候需要处理html。光查看是不用处理的,直接是什么就加载什么!
        if([self.state isEqualToString:@"未办理"]){
            //NSLog(@"办理时候需要处理html:杂质过滤,加入只读,加入JS脚本.");
            //html_1 杂质过滤
            filterHTML= [[[[[[[formInfo.FileContent replaceCaseInsensitive:@"readonly=\"\"" :@""] replaceCaseInsensitive:@"readonly" :@""] replaceRegex:@"BACKGROUND-COLOR: #EFEFEF(;)?" :@""] replaceRegex:@"style=\"\"" :@""] replaceRegex:@"class=\"wjjbg\"" :@""] replaceRegex:@"\\s(=\"\")+" :@""] replaceRegex:@"\".+?/WebUI/userfiles" :@"\"/WebUI/userfiles"];
            //html_2 加入只读。首先发起只读列表请求。已委托没有UpNodeId，没有数据，自然解析异常。
            globalRequest=[WebServicesUtils getReadOnlyFormName:[NSString stringWithFormat:@"getReadOnly @UpNodeId=%@",formInfo.UpNodeId] withDelegete:self];
        }else{//已办理，已委托 直接加载原页面
            //NSLog(@"直接加载原页面(当然,补充一下样式。)");
            [self.formContent loadHTMLString:[NSString stringWithFormat:@"<html>"
                                              "<head>"
                                              "<style>.wjjbg { background-color: #EFEFEF }</style>"
                                              "</head><body>%@</body>"
                                              "</html>",formInfo.FileContent] baseURL:[NSURL URLWithString:domain_url]];
        }
    }else if(request.tag==1){//只读列表请求结束
        NSString* responseStr=[request responseString];
        ////NSLog(@"只读responseStr=%@",responseStr);
        NSArray* readOnlyForm=[JsonParser parseAsReadOnlyForm:responseStr];
        //加入只读属性
        for(NSString* item in readOnlyForm){
            ////NSLog(@"只读item=%@",item);
            filterHTML=[filterHTML replaceCaseInsensitive:[NSString stringWithFormat:@"name=\"%@\"",item] :[NSString stringWithFormat:@"name=\"%@\" style=\"BACKGROUND-COLOR: #EFEFEF\" readonly=\"\" class=\"wjjbg\"",item]];
        }
        //html_3 加入JS脚本
        NSString* fullHTML=[NSString stringWithFormat:@"<html>"
                            "<head>"
//                            "<meta name='viewport' content='minimum-scale=0.6, maximum-scale=5,initial-scale=1,user-scalable=yes,width=320'>"
                            "<style>.wjjbg { background-color: #EFEFEF }</style>"
                            "<script type='text/javascript'>"
                            //移除只读属性
                            "function removeReadonly() { "
                            "  var tas= document.getElementsByTagName('TextArea');"
                            "    for (var i=0;i<tas.length;i++ )"
                            "    {tas[i].removeAttribute('readonly');} "
                            "  var is= document.getElementsByTagName('Input');"
                            "    for (var j=0;j<is.length;j++ )"
                            "   { is[j].removeAttribute('readonly');}"
                            "}"
                            // 服务器脚本 本地化（适用于Android）
                            "function DateSelect(eleId) {"
                            "    var dateChoose = document.getElementById(eleId);"
                            "javascript:window.aliasInHtml.chooseDate(dateChoose.value,dateChoose.id);"
                            "  }"
                            // 设置时间
                            "  function setDate(dateStr,eleId){"
                            "    var dateChoose = document.getElementById(eleId);"
                            "     dateChoose.setAttribute('value',dateStr);"
                            " }"
                            // 同步Dom值脚本
                            "function JSHtml() {"
                            //      textArea 同步值
                            "var elsTA= document.getElementsByTagName('TextArea');"
                            "for (var i=0;i<elsTA.length;i++ )  "
                            "{elsTA[i].innerHTML=elsTA[i].value;}"
                            //      input 同步值
                            "var elsInput= document.getElementsByTagName('Input');"
                            "for (var i=0;i<elsInput.length;i++ )"
                            "{elsInput[i].setAttribute('value',elsInput[i].value);}"
                            //      select 同步值
                            "var selects =document.getElementsByTagName('select');"
                            " for (var s = 0; s < selects.length; s++) {"
                            " var selectItem = selects[s];"
                            " for (var k = 0; k < selectItem.options.length; k++){"
                            "     if (selectItem.options[k].selected) {"
                            "  selectItem.options[k].setAttribute('selected', '');}"
                            "else{selectItem.options[k].removeAttribute('selected')}"
                            "}"
                            "}"
                            "}"
                            "</script>"
                            "</head>"
                            "<body>"
                            "<wjj>%@</wjj>"
                            "</body> "
                            "</html> ",filterHTML];
        ////NSLog(@"%@",fullHTML);
        //[self.formContent setScalesPageToFit:YES];
        [self.formContent loadHTMLString:fullHTML baseURL:[NSURL URLWithString:domain_url]];
        
    }else if (request.tag==2){//保存请求结束
        NSString* responseStr=[request responseString];
        ////NSLog(@"responseStr=%@",responseStr);
        ProcessResult* pr= [JsonParser parseAsProcessResult:responseStr];
        UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
        [Tools toastNotification:pr.msg andView:shareWindow andLoading:NO andIsBottom:NO andHideTime:5];
        if(pr.result==1){
            //返回待办列表
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else if (request.tag==3){//保存并通过请求结束
        NSString* responseStr=[request responseString];
        //NSLog(@"responseStr=%@",responseStr);
        ProcessResult* pr= [JsonParser parseAsProcessResult:responseStr];
        UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
        [Tools toastNotification:pr.msg andView:shareWindow andLoading:NO andIsBottom:NO andHideTime:5];
        if(pr.result==1){
            //转到下一步流程
            SpNext* spNext=[[SpNext alloc] init];
            spNext.userForm=formInfo;
            [self.navigationController pushViewController:spNext animated:YES];
        }
        
    }else if (request.tag==4){//保存并驳回请求结束
        NSString* responseStr=[request responseString];
        ////NSLog(@"responseStr=%@",responseStr);
        ProcessResult* pr= [JsonParser parseAsProcessResult:responseStr];
        UIWindow *shareWindow = [UIApplication sharedApplication].keyWindow;
        [Tools toastNotification:pr.msg andView:shareWindow andLoading:NO andIsBottom:NO andHideTime:5];
        if(pr.result==1){
            //转到下一步流程
            //转到下一步流程
            SpBhNext* spBhNext=[[SpBhNext alloc] init];
            spBhNext.userForm=formInfo;
            [self.navigationController pushViewController:spBhNext animated:YES];
        }
        
    }
    
}

-(void)requestFailed:(ASIHTTPRequest *)request{
    
    if(hud){
        [hud hide:YES];
    }
    
    [Tools toastNotification:@"处理请求失败，请检查网络连接!" andView:self.view andLoading:NO andIsBottom:NO];
}

#pragma mark-- 返回到上一个视图
-(void)backTo{
    if(self.formContent.canGoBack){
        [self.formContent goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}


@end
